package com.starrin.tennisfinder.scheduler;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.starrin.tennisfinder.extractors.ExtractorBokaTennis;
import com.starrin.tennisfinder.model.VenueAvailabilityDataHolder;
import com.starrin.tennisfinder.system.Cache;
import com.starrin.tennisfinder.util.DateUtil;
import com.starrin.tennisfinder.util.WebUtil;
import org.apache.log4j.Logger;

import java.net.URL;
import java.util.*;

/**
 * Created by larsstarrin on 22/03/14.
 */
public class RefreshBokaTennis implements Runnable {

    private Cache cache = Cache.getInstance();
    private static final Logger logger = Logger.getLogger(RefreshTennisStadion.class);
    private String venueKey;     private static final int FORESIGHT_DAYS = 15;
    private Map<String, VenueAvailabilityDataHolder> newData = new HashMap<>();

    public RefreshBokaTennis(String venueKey) {
        this.venueKey = venueKey;
    }

    public void run() {
        logger.info("Start refreshing availability data for " + venueKey);
        try {
            long start = System.currentTimeMillis();
            refresh();
            //Put temp data into cache
            for (Map.Entry<String, VenueAvailabilityDataHolder> entry : newData.entrySet()) {
                cache.putEntry(entry.getKey(), venueKey, entry.getValue());
            }
            logger.info("Finished refreshing availability data for " + venueKey + " in " +  (System.currentTimeMillis() - start) / 1000 + " seconds");

        } catch (Exception e) {
            logger.error("Error fetching data", e);
        }
    }

    private void refresh() throws Exception {
        WebClient webClient = new WebClient();
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setJavaScriptEnabled(false);

        //Login
        WebRequest loginRequest = new WebRequest(new URL("http://bokatennis.nu/smedslattentennis/login.php"), HttpMethod.POST);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new NameValuePair("username", "lstarrin"));
        params.add(new NameValuePair("password", "lap1nkulta"));
        loginRequest.setRequestParameters(params);
        webClient.getPage(loginRequest);

        for (int i = 0; i < FORESIGHT_DAYS; i++) {
            Calendar cal = new GregorianCalendar();
            cal.add(Calendar.DAY_OF_MONTH, i);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            String timeInSeconds = String.valueOf(cal.getTimeInMillis()/1000);
            String url = "http://bokatennis.nu/smedslattentennis/index.php?date=" + timeInSeconds;
            String response = webClient.getPage(url).getWebResponse().getContentAsString();
            response = WebUtil.getReducedResponse(response, "td class=\"radrubrik\">Tid</td>");
            VenueAvailabilityDataHolder dataHolder = new ExtractorBokaTennis().extractVenueAvailability(response, url);
            newData.put(new DateUtil().getAsString(cal.getTime()), dataHolder);
        }
    }

}
